package com.thiswhyme.demo.msgpush.core.impl.nio.event;

import com.thiswhyme.demo.msgpush.core.event.AbstractPushEventWsHandler;
import com.thiswhyme.demo.msgpush.core.event.bean.WebSocketEvent;
import com.thiswhyme.demo.msgpush.core.impl.nio.ChannelManager;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

/**
 * @description: WebSocket消息推送事件处理器-nio
 * @author: thiswhyme
 * @date: 2021/9/28
 */
@Slf4j
public class PushEventNioHandler extends AbstractPushEventWsHandler {

    @Override
    public void doHandle(WebSocketEvent event) {
        event.getIdentifiers().forEach(identifier -> {
            Channel channel = ChannelManager.get(identifier);
            if (null != channel) {
                if (channel.isOpen()) {
                    channel.writeAndFlush(new TextWebSocketFrame(event.getMsgContent()));
                    log.debug("【{}】完成推送", identifier);
                } else {
                    log.error("【{}】推送失败，Channel已关闭", identifier);
                }
            } else {
                log.debug("【{}】Channel已关闭或不在该实例上，跳过推送", identifier);
            }
        });
    }
}
